package logic

import (
	"Junior_two/subject/cart/cartrpc/dao"
	"Junior_two/subject/cart/cartrpc/model"
	"Junior_two/subject/cart/cartrpc/utils"
	"context"
	"fmt"
	"net/http"

	"Junior_two/subject/cart/cartrpc/internal/svc"
	"Junior_two/subject/cart/cartrpc/pb/cartRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type InsertLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewInsertLogic(ctx context.Context, svcCtx *svc.ServiceContext) *InsertLogic {
	return &InsertLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *InsertLogic) Insert(in *cartRpc.InRequest) (*cartRpc.Response, error) {
	// todo: add your logic here and delete this line
	//调用方法 根据上品id 进行查询 库存是否充足
	LKey := "Number:good_id" + fmt.Sprintf("%d", in.GoodId)
	num, err := utils.RedisLLen(LKey)
	if err == false || num < in.Count {
		return &cartRpc.Response{
			Msg:  "库存不足",
			Code: http.StatusAccepted,
		}, nil
	}
	//根据 商品id 查数据
	g := dao.MyId(in.GoodId)
	//求出总价
	totalAmount := g.Price * float64(in.Count)
	//库存充足 进行添加购物车
	c := model.Cart{
		Count:       in.Count,
		TotalAmount: totalAmount,
		G:           g,
	}

	//减少库存
	for i := 1; i <= int(in.Count); i++ {
		utils.RedisLPop(LKey)
	}
	//储存
	HKeY := "cart:user_id" + fmt.Sprintf("%d", in.UserId)
	if !utils.RedisHSet(HKeY, c, in.GoodId) {
		return &cartRpc.Response{
			Msg:  "添加失败",
			Code: http.StatusAlreadyReported,
		}, nil
	}
	//寻龙分金看缠山
	return &cartRpc.Response{
		Msg:  "添加成功",
		Code: http.StatusOK,
	}, nil
}
